package joodle.si;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Collection;

import javax.imageio.ImageIO;
import javax.swing.JComponent;

import joodle.domain.Canvas;
import joodle.domain.Shape;
import joodle.ui.CanvasComponent;

/**
 * This is a utility class with methods for loading shapes from XML files and saving shapes into XML 
 * (SVG) files and exporting the Canvas as an image file. This class uses the ShapeBuilder interface 
 * for loading shapes from an input stream. Other loaders for Shape objects from other formats can be 
 * provided by classes that implement this interface. The ShapeBuilder interface and SVGParser reify 
 * the builder design pattern; It makes it easy to extend this class hierarchy to provide support for 
 * probable future file formats that can be loaded.
 * <p><center>
 * <img src="http://ug.bcc.bilkent.edu.tr/~m_ozdal/Site/Reports_files/design_files/image014.jpg" />
 * </center></p>
 */
public class IOManager {
	
	private static final String SVG_HEADER = "<?xml version=\"1.0\" standalone=\"yes\"?>\n";
	
	/**
	 * Loads a collection of shapes from XML file
	 * @param f XML file to be loaded
	 * @return shapes that are parsed
	 * @throws SVGParseException
	 * @throws FileNotFoundException
	 */
	public static Collection<Shape> loadXML(final File f) throws SVGParseException, FileNotFoundException {
		ShapeBuilder sb = SVGParser.instance();
		return sb.parse(f);
	}
	
	/**
	 * Saves the canvas into XML file
	 * @param f XML file that the canvas is saved into
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void saveXML(final File f) throws FileNotFoundException, IOException {
		Writer sw = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(f)));
		
		sw.write(SVG_HEADER);
		sw.write(Canvas.instance().asXML());
		sw.close();
	}

	/**
	 * Exports the canvas as an image file
	 * @param f an image file that the canvas is saved into
	 * @throws IOException
	 */
	public static void saveImage(final File f) throws IOException {
		JComponent cc = CanvasComponent.instance(); 
		BufferedImage bi = new BufferedImage(cc.getWidth(), cc.getHeight(), BufferedImage.TYPE_INT_ARGB);
		
		Graphics g = bi.createGraphics();
		Canvas.instance().drawAll(g);
		g.dispose();
		
		ImageIO.write(bi, "png", f);
	}
}
